package leetcode;

/**
 * leetcode43题解题
 */
public class LCode43 {
    public static void main(String[] args) {
        String num1 = "0";
        String num2 = "3";
        String multiply = multiply(num1, num2);
        System.out.println(multiply);
    }
    // 两个字符串相乘
    public static String multiply(String num1, String num2) {
        // 两个数字中任意一个为0，乘积都为0
        if ("0".equals(num1) || "0".equals(num2)) {
            return "0";
        }
        String str = "";
        for (int i = num1.length() - 1; i >= 0; i--) {
            int carry = 0;
            StringBuffer sb = new StringBuffer();
            for (int j = num2.length() - 1; j >= 0; j--) {
                int multi = (num1.charAt(i) - '0') * (num2.charAt(j) - '0') + carry;
                carry = multi / 10;
                sb.append(multi % 10);
            }
            if (carry != 0) {
                sb.append(carry);
            }
            sb.reverse();
            for (int k = 1; k < num1.length() - i; k++) {
                sb.append("0");
            }
            str = addStr(str, sb.toString());
        }
        return str;
    }
    // 两个字符串相加
    public static String addStr(String str1, String str2) {
        int i = str1.length() - 1;
        int j = str2.length() - 1;
        int remain = 0;
        StringBuffer sb = new StringBuffer();
        while (i >= 0 || j >= 0) {
            if (i >= 0 && j >= 0) {
                int sum = str1.charAt(i) - '0' + str2.charAt(j) - '0' + remain;
                remain = sum / 10;
                sb.append(sum % 10);
                i--;
                j--;
            } else if (i >= 0 && j < 0) {
                int sum = str1.charAt(i) - '0' + remain;
                remain = sum / 10;
                sb.append(sum % 10);
                i--;
            }else if (i < 0 && j >= 0) {
                int sum = str2.charAt(j) - '0' + remain;
                remain = sum / 10;
                sb.append(sum % 10);
                j--;
            }
        }
        if (remain != 0) {
            sb.append(remain);
        }
        return sb.reverse().toString();
    }
}